package lk.icta.core.web.action;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import lk.icta.common.AppConstants;
import lk.icta.common.web.WebConstants;
import lk.icta.user.common.Constant;
import lk.icta.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;


public class LoginInterceptor extends AbstractInterceptor {

    //private static final long serialVersionUID = -384351385648411403L;
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    private String username;


    @SuppressWarnings("unchecked")
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        String returnString = null; // variable hold the return value
        try {
            // variable hold the current action
            String currentAction = invocation.getProxy().getActionName();
            if (logger.isDebugEnabled()) {
                logger.debug("Currently processing action - {}", currentAction);
            }

            if (!WebConstants.EXCLUDE_SESSION_CHECK.contains(currentAction)) {
                // Get the session object from the invocation
                final Map<String, Object> sessionMap = invocation.getInvocationContext()
                        .getSession();

                // Is there a "user" object stored in the user's HttpSession?
                User user = (User) sessionMap.get(AppConstants.SESSION_USER_BEAN);
                //invocation.getInvocationContext().setSession(sessionMap);

                if (user == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("user object not found");
                    }
                    returnString = "invalid-session";
                } else {
                    if (!WebConstants.EXCLUDE_FIRST_LOGIN_CHECK.contains(currentAction)) {
                        if (user.getLoginState() == User.LoginState.FIRST_LOGIN) {
                            username = user.getUsername();
                            returnString = "first-login";
                        }
                    }
                }
            }
            if (returnString == null) {
                returnString = invocation.invoke();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return returnString;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
